package com.yin.myproject.core;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author Eason
 * @create 2018-04-08 11:40
 **/
public class ScheduledMethodRunnable implements Runnable {

    private final String key;

    private final Object target;

    private final Method method;

    private final Object[] params;

    public ScheduledMethodRunnable(String key, Object target, Method method, Object[] params) {
        this.key = key;
        this.target = target;
        this.method = method;
        this.params = params;
    }

    public ScheduledMethodRunnable(String key, Object target, String methodName, Object[] params) throws NoSuchMethodException {
        this.key = key;
        this.target = target;
        this.method = target.getClass().getMethod(methodName);
        this.params = params;
    }

    /**
     * @return the key
     */
    public String getKey() {
        return key;
    }

    public Object getTarget() {
        return this.target;
    }

    public Method getMethod() {
        return this.method;
    }

    public Object[] getParams() {
        return params;
    }

    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(this.method);
            if (this.getParams() != null) {
                this.method.invoke(this.target, this.getParams());
            } else {
                this.method.invoke(this.target);
            }
        } catch (InvocationTargetException ex) {
            ReflectionUtils.rethrowRuntimeException(ex.getTargetException());
        } catch (IllegalAccessException ex) {
            throw new UndeclaredThrowableException(ex);
        }
    }

}
